package com.holly.unit.bpmn.designer.core.facade;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.holly.unit.bpmn.activiti.context.ActivitiContext;
import com.holly.unit.bpmn.designer.constants.BpmnDesignerConstants;
import com.holly.unit.bpmn.designer.core.adapter.BpmnDesignerAdapter;
import com.holly.unit.bpmn.designer.core.adapter.BpmnDesignerXml;
import com.holly.unit.bpmn.designer.core.bpmn.BpmnModelActImpl;
import com.holly.unit.bpmn.designer.core.bpmn.BpmnModelFactory;
import com.holly.unit.bpmn.designer.model.BpmnDesignerModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;

import java.util.Objects;

/**
 * 类描述: 流程设计器高层接口 实现类
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/5/12 19:29
 */
public class BpmnDesignerFacadeApiImpl implements BpmnDesignerFacadeApi {


    private static RepositoryService repositoryService = ActivitiContext.repositoryService();

    @Override
    public boolean deploy(String json) {
        BpmnDesignerModel model = JSON.parseObject(json,BpmnDesignerModel.class);
        return deploy(model);
    }

    @Override
    public boolean deploy(BpmnDesignerModel model) {
        BpmnModelFactory factory = new BpmnModelActImpl();
        BpmnDesignerXml xml = new BpmnDesignerXml(factory);
        String bpmn = BpmnDesignerAdapter.bpmn(model, xml);

        if (StrUtil.isBlank(bpmn)) {
            return false;
        }
        // 部署发布模型流程
        String processName = model.getBasicInfo().getFlowName();
        String bpmnName = model.getBasicInfo().getFlowName() + BpmnDesignerConstants.BPMN_FILE_NAME_SUFFIX;
        Deployment deployment = repositoryService.createDeployment()
                .name(processName)
                .addString(bpmnName, bpmn)
                .deploy();
        return (Objects.nonNull(deployment)?true:false);
    }
}
